<template>
  <div>
    <el-dialog v-model="dialogVisible" title="添加物料" :width="'70%'" class="allocation-dialog" :close-on-click-modal="false">
      <div>
        <el-tabs v-model="activeLevel" class="level-tabs">
          <el-tab-pane label="内部材料" name="in">
            <el-table
              highlight-current-row
              v-if="currentAllocation"
              :data="totalEnergyData"
              border
              class="allocation-table"
              ref="table1"
              @selection-change="handleSelectionChange1"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="id" label="编号" />
              <el-table-column prop="name" label="材料编号" />
              <el-table-column prop="value" label="材料名称" />
              <el-table-column prop="unit" label="材料类型" />
            </el-table>
            <el-empty v-else description="暂无数据" />
          </el-tab-pane>
          <el-tab-pane label="外购材料" name="out">
            <el-table
              highlight-current-row
              v-if="outAllocation"
              :data="outEnergyData"
              ref="table2"
              border
              class="allocation-table"
              @selection-change="handleSelectionChange2"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="name" label="材料编号" />
              <el-table-column prop="value" label="材料名称" />
              <el-table-column prop="unit" label="材料类型" />
            </el-table>
            <el-empty v-else description="暂无数据" />
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 底部按钮区域 -->
      <template #footer>
        <span class="dialog-footer">
          <template v-if="!isInputMode">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleEnterInput">添加</el-button>
          </template>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { getMaterialListData } from "@/utils/localStorageHandler";
import { ElMessage } from "element-plus";

const materialList = ref(getMaterialListData());
const dialogVisible = ref(false);
const isInputMode = ref(false);
/**树中已经出现过的叶子 */
const currentParams = ref();
const table1 = ref();
const table2 = ref();
const selectedItems1 = ref([]);
const selectedItems2 = ref([]);
const emit = defineEmits(["node_add"]);

/**
 * 当前选中的层次
 */
const activeLevel = ref("");

/**
 * 找到所有未分配的物料
 */
const currentAllocation = computed(() => {
  return materialList.value.filter(item => item.sourceType === 1 && !currentParams.value.leaves.includes(item.id));
});
const outAllocation = computed(() => {
  return materialList.value.filter(item => item.sourceType === 2 && !currentParams.value.leaves.includes(item.id));
});

// 获取第一个可见的 tab
const getFirstVisibleTab = computed(() => {
  return "in"; // 默认显示tab
});

// 自制数据展示
const totalEnergyData = computed(() => {
  const totalEnergy = currentAllocation.value;
  if (!totalEnergy) return [];
  return totalEnergy.map(item => ({
    id: item.id,
    name: item.materialId,
    value: item.materialName,
    unit: item.materialType
  }));
});
const outEnergyData = computed(() => {
  const totalEnergy = outAllocation.value;
  if (!totalEnergy) return [];
  return totalEnergy.map(item => ({
    id: item.id,
    name: item.materialId,
    value: item.materialName,
    unit: item.materialType
  }));
});

const handleEnterInput = () => {
  if (selectedItems1.value.length === 0 && selectedItems2.value.length === 0) {
    ElMessage({
      type: "warning",
      message: "请选择一个物料!"
    });
    return;
  }
  dialogVisible.value = false;
  console.log(selectedItems1.value);
  console.log(selectedItems2.value);
  emit("node_add", selectedItems1.value, selectedItems2.value);
};

// 打开对话框方法
const openDialog = (params: string[]) => {
  currentParams.value = params;
  activeLevel.value = getFirstVisibleTab.value;
  dialogVisible.value = true;
};

function handleSelectionChange1(selection: any) {
  if (selection.length > 1) {
    let del_row = selection.shift();
    table1.value.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
  }
  selectedItems1.value = selection;
}
function handleSelectionChange2(selection: any) {
  if (selection.length > 1) {
    let del_row = selection.shift();
    table2.value.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
  }
  selectedItems2.value = selection;
}

// 暴露方法给父组件
defineExpose({
  openDialog
});
</script>

<style scoped lang="scss">
.allocation-dialog :deep(.el-dialog) {
  position: relative !important;
  top: 10vh !important;
  display: flex;
  flex-direction: column;
  height: 600px !important;
}

/* 录入模式时调整位置 */
.allocation-dialog :deep(.el-dialog)[aria-label="分配数据管理"] {
  top: 5vh !important;
}
.allocation-dialog :deep(.el-dialog__header) {
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #dcdfe6;
}
.allocation-dialog :deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #dcdfe6;
}
.allocation-dialog :deep(.el-tabs) {
  display: flex;
  flex-direction: column;
}
.allocation-dialog :deep(.el-tabs__content) {
  flex: 1;
}
.allocation-dialog :deep(.el-tab-pane) {
  padding: 20px 0;
}
.allocation-table {
  width: 100%;
}
.level-tabs {
  margin-bottom: 20px;
}
.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}
.info-bar {
  display: flex;
  justify-content: space-around;
  padding: 10px 0;
  margin: 20px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.info-item {
  font-size: 14px;
}
.info-item strong {
  margin-right: 8px;
  font-weight: bold;
  color: #333333;
}

/* 总用量表格样式优化 */
.allocation-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}
.allocation-table :deep(.el-table__row) {
  height: 50px;
}
.el-table__header-wrapper .el-checkbox {
  display: none;
}
</style>
